<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2021/9/28
 * Time: 10:32
 */

namespace Edmmss\Easyswoole\Task\Client;

class Response
{
    /**
     * 返回成功的状态码
     */
    const RESPONSE_CODE_OK = 200; // 200

    const ERR_CONNECT = 118; // 连接服务器失败
    const ERR_TOOBIG = 413; // 超过最大允许的长度
    const ERR_ROUTE = 404; // 错误的call 方法，不存在该路由
    const ERR_CALL = 405; // 错误的call 方法，不支持async
    const ERR_SEND = 417; // 发送失败
    const ERR_UNPACK = 428; // 解包失败了
    const ERR_CLOSED = 500; // 连接被关闭
    const ERR_TIMEOUT = 504; // 服务器端超时
    const ERR_DATA_PARSE = 101; // 数据解析失败
    const ERR_DATA_HEADER = 102; // 数据header头解析失败
    const ERR_DATA_DATA = 103; // 数据data解析失败

    /**
     * @var array
     */
    public static $statuses = [
        self::RESPONSE_CODE_OK => '0K', // 200
        self::ERR_CONNECT      => 'Connection timed out', // 连接服务器失败
        self::ERR_TOOBIG       => 'Request Entity Too Large', // 超过最大允许的长度
        self::ERR_ROUTE        => 'Not Found', // 没有该路由
        self::ERR_CALL         => 'method Async is not supported', // 不支持该请求方式,不支持async
        self::ERR_SEND         => 'Expectation failed', // 发送失败
        self::ERR_UNPACK       => 'Precondition Required', // 解包失败了, 错误的协议头
        self::ERR_CLOSED       => 'Internal Server Error', // 连接被关闭
        self::ERR_TIMEOUT      => 'Gateway Time-out', // 服务器端超时
        self::ERR_DATA_HEADER  => 'Data Header interpretation failure',
        self::ERR_DATA_DATA    => 'Data Data interpretation failure',
    ];

    /**
     * @var 请求返回码
     */
    private $_code;

    /**
     * @var bool 是否返回成功
     */
    private $_isSuccess = false;

    /**
     * @var array 返回数据
     */
    private $_data;

    /**
     * @var array 返回header
     */
    private $_header;

    /**
     * @var string 成功信息
     */
    private $_success;

    /**
     * @var int 错误码
     */
    private $_errorCode;

    /**
     * @var string 错误信息
     */
    private $_errorMessage;

    /**
     * @var string 请求路由
     */
    private $_call;

    /**
     * Response constructor.
     * @param array $content [
     *      'success' => '',
     *      'data' => ''
     *  ][
     *      'errorCode' => '',
     *      'errorMessage' => ''
     *  ]
     * @throws \Exception
     */
    public function __construct(array $data, array $header)
    {
        if (isset($data['code'])
            && isset($data['call'])
            && $data['code'] == self::RESPONSE_CODE_OK
            && isset($data['data'])) {
            $content = $data['data'];
            if (isset($content['errorCode']) && isset($content['errorMessage'])) {
                $this->_errorCode = $content['errorCode'];
                $this->_errorMessage = $content['errorMessage'];
                $this->_header = $header;
            } elseif (is_array($content)) {
                $this->_success = true;
                $this->_data = $content;
                $this->_isSuccess = true;
                $this->_header = $header;
                $this->_call = $data['call'];
            } else {
                throw new \Exception('错误的结构');
            }
        } elseif (isset($data['code']) && $data['code'] != self::RESPONSE_CODE_OK) {
            $this->_code = $data['code'];
        } else {
            throw new \Exception('返回数据不正确');
        }
    }

    /**
     * 获取是否成功
     *
     * @date   2018/8/4
     * @return bool
     * @author edmmss
     */
    public function getIsSuccess()
    {
        return $this->_isSuccess;
    }

    /**
     * 获取成功信息
     *
     * @date   2018/8/4
     * @return string
     * @author edmmss
     */
    public function getSuccessMessage()
    {
        return $this->_success;
    }

    /**
     * 获取请求返回的数据
     *
     * @date   2018/8/4
     * @return array
     * @author edmmss
     */
    public function getData()
    {
        return $this->_data;
    }

    /**
     * 获取错误码
     *
     * @date   2018/8/4
     * @return int
     * @author edmmss
     */
    public function getErrorCode()
    {
        return $this->_errorCode;
    }

    /**
     * 获取逻辑错误信息（就是rpc主动报错）
     *
     * @date   2018/8/4
     * @return string
     * @author edmmss
     */
    public function getErrorMessage()
    {
        return $this->_errorMessage;
    }

    /**
     * 判断是否是逻辑错误（就是rpc主动报错）
     *
     * @date   2018/8/27
     * @return bool
     * @author edmmss
     */
    public function isLogicError()
    {
        return $this->_errorMessage ? true : false;
    }

    /**
     * 获取请求路由
     *
     * @date   2018/9/11
     * @return mixed|string
     * @author edmmss
     */
    public function getCall()
    {
        return $this->_call;
    }

    /**
     * 获取连接通信错误信息
     *
     * @date   2018/8/27
     * @return array|null
     * @author edmmss
     */
    public function getError()
    {
        if ($this->_code == self::RESPONSE_CODE_OK) {
            // 请求成功，没有错误信息
            return null;
        } else {
            return [
                'code'        => $this->_code,
                'codeMessage' => isset(self::$statuses[$this->_code]) ? self::$statuses[$this->_code] : '',
                'data'        => $this->_data,
            ];
        }
    }
}